package com.github.cakin.shiro.chapter20.filter;

import com.github.cakin.shiro.chapter20.Constants;
import com.github.cakin.shiro.chapter20.realm.StatelessToken;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: StatelessAuthcFilter
 * @description: 类似于 FormAuthenticationFilter，根据当前请求上下文信息进行登录认证的过滤器。
 * @date: 2020/5/29
 * @author: cakin
 */
public class StatelessAuthcFilter extends AccessControlFilter {
    /**
     * 功能描述：控制访问允许的流向
     *
     * @param request     请求
     * @param response    响应
     * @param mappedValue mappedValue
     * @return boolean 如果为false，将会调用onAccessDenied
     * @author cakin
     * @date 2020/5/29
     */
    @Override
    protected boolean isAccessAllowed( ServletRequest request, ServletResponse response, Object mappedValue ) throws Exception {
        return false;
    }

    /**
     * 功能描述：登录控制流程
     * 获取客户端传入的用户名、请求参数、消息摘要，生成 StatelessToken；然后交给相应的 Realm 进行认证
     *
     * @param request  请求
     * @param response 响应
     * @return boolean 如果为false，将会调用onAccessDenied
     * @author cakin
     * @date 2020/5/29
     */
    @Override
    protected boolean onAccessDenied( ServletRequest request, ServletResponse response ) throws Exception {
        // 1、客户端生成的消息摘要
        String clientDigest = request.getParameter(Constants.PARAM_DIGEST);
        // 2、客户端传入的用户身份
        String username = request.getParameter(Constants.PARAM_USERNAME);
        // 3、客户端请求的参数列表
        Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());
        // 移除客户端生成的消息摘要
        params.remove(Constants.PARAM_DIGEST);

        // 4、生成无状态Token
        StatelessToken token = new StatelessToken(username, params, clientDigest);

        try {
            // 5、委托给Realm进行登录
            getSubject(request, response).login(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 6、登录失败
            onLoginFail(response);
            return false;
        }
        return true;
    }

    /**
     * 功能描述：登录失败时默认返回401状态码
     *
     * @param response 响应
     * @author cakin
     * @throws IOException 异常
     * @date 2020/5/29
     */
    private void onLoginFail( ServletResponse response ) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login error");
    }
}
